package com.csp.mingyue.search.controller;

import cn.easyes.core.conditions.LambdaEsQueryWrapper;
import com.csp.mingyue.common.core.vo.R;
import com.csp.mingyue.search.api.vo.Document;
import com.csp.mingyue.search.esmapper.DocumentMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * ES CRUD 演示案例
 *
 * @author njy
 * @date 2023/9/18 09:59
 */
@Tag(name = "ES CRUD 演示案例")
@RestController
@RequestMapping("/crudDemo")
@RequiredArgsConstructor
public class EsCrudDemoController {

	private final DocumentMapper documentMapper;

	@GetMapping("/accurate")
	@Operation(summary = "精确查询", parameters = { @Parameter(name = "title", description = "标题", required = true) })
	public R<Document> accurate(String title) {
		LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
		wrapper.eq(Document::getTitle, title);
		return R.ok(documentMapper.selectOne(wrapper));
	}

	@GetMapping("/fuzzy")
	@Operation(summary = "模糊查询", parameters = { @Parameter(name = "key", description = "搜索关键字", required = true) })
	public R<List<Document>> fuzzy(String key) {
		LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
		wrapper.like(Document::getTitle, key);
		return R.ok(documentMapper.selectList(wrapper));
	}

	@PostMapping("/add")
	@Operation(summary = "添加")
	public R<Boolean> insert(@RequestBody Document document) {
		return R.ok(documentMapper.insert(document) > 0);
	}

	@PutMapping("/update")
	public R<Boolean> update(@RequestBody Document document) {
		return R.ok(documentMapper.updateById(document) > 0);
	}

	@DeleteMapping("/delete/{id}")
	@Operation(summary = "删除文档",
			parameters = { @Parameter(in = ParameterIn.PATH, name = "id", description = "ID", required = true) })
	public R<Boolean> delete(@PathVariable String id) {
		return R.ok(documentMapper.deleteById(id) > 0);
	}

}
